package com.matrix.yukun.matrix.main_module.dialog;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.matrix.yukun.matrix.AppConstant;
import com.matrix.yukun.matrix.MyApp;
import com.matrix.yukun.matrix.R;
import com.matrix.yukun.matrix.download_module.bean.FileInfo;
import com.matrix.yukun.matrix.download_module.service.DownLoadUtils;
import com.matrix.yukun.matrix.main_module.utils.SPUtils;
import com.matrix.yukun.matrix.main_module.utils.ToastUtils;
import com.matrix.yukun.matrix.tool_module.barrage.dialog.BaseBottomDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;


/**
 * author: kun .
 * date:   On 2018/11/16
 */
public class ShareDialog extends BaseBottomDialog implements View.OnClickListener {

    private static ShareDialog shareDialog;
    private String mTitle;
    private String mShareUrl;
    private ImageView mIvQQ;
    private ImageView mIvZone;
    private ImageView mIvMore;
    private String mImageUrl;
    private String mImagePath;
    private ImageView mIvWeixin;
    private ImageView mIvFriend;
    private RelativeLayout mRlBanner;
    public static final String PACKAGE_WECHAT = "com.tencent.mm";//微信
    public static final String PACKAGE_MOBILE_QQ = "com.tencent.mobileqq";//qq

    public static ShareDialog getInstance(String title, String shareUrl, String imageUrl) {
        if (shareDialog == null) {
            shareDialog = new ShareDialog();
        }
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putString("imageUrl", imageUrl);
        bundle.putString("shareUrl", shareUrl);
        shareDialog.setArguments(bundle);
        return shareDialog;
    }

    public static ShareDialog getImageInstance(String imagepath, String shareUrl) {

        if (shareDialog == null) {
            shareDialog = new ShareDialog();
        }
        Bundle bundle = new Bundle();
        bundle.putString("imagepath", imagepath);
        bundle.putString("shareUrl", shareUrl);
        shareDialog.setArguments(bundle);
        return shareDialog;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        mTitle = arguments.getString("title");
        mShareUrl = arguments.getString("shareUrl");
        mImageUrl = arguments.getString("imageUrl");
        mImagePath = arguments.getString("imagepath");
    }

    @Override
    public int setLayout() {
        return R.layout.share_dialog;
    }

    @Override
    protected void initView(View inflate, Bundle savedInstanceState) {
        mIvQQ = inflate.findViewById(R.id.iv_share_qq);
        mIvZone = inflate.findViewById(R.id.iv_share_zone);
        mIvMore = inflate.findViewById(R.id.iv_share_more);
        mIvWeixin = inflate.findViewById(R.id.iv_share_weixin);
        mIvFriend = inflate.findViewById(R.id.iv_share_friend);
        mRlBanner = inflate.findViewById(R.id.rl);
        mRlBanner.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        mIvQQ.setOnClickListener(this);
        mIvZone.setOnClickListener(this);
        mIvMore.setOnClickListener(this);
        mIvWeixin.setOnClickListener(this);
        mIvFriend.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_share_qq:
//                if(!TextUtils.isEmpty(mImagePath)){
//                    shareImageToQQ(QQ.NAME);
//                }else {
//                    shareToQQ(QQ.NAME);
//                }
                break;
            case R.id.iv_share_zone:
//                if(!TextUtils.isEmpty(mImagePath)){
//                    shareImageToQQ(QZone.NAME);
//                }else {
//                    shareToQQ(QZone.NAME);
//                }
                break;
            case R.id.iv_share_weixin://好友
                if (!TextUtils.isEmpty(mImagePath)) {
                    shareLocalImageToWeiXin();
                } else {
                    shareToWeiXin();
                }
                break;
            case R.id.iv_share_friend://朋友圈
                if (!TextUtils.isEmpty(mImagePath)) {
                    shareLocalImageToWeiXinFriend(mImagePath, "MatrixPhoto");
                } else {
                    shareToWeiXinFriend();
                }
                break;
            case R.id.iv_share_more:
                shareToMore();
                break;
            default:
                break;
        }
        getDialog().dismiss();
    }

    private void shareToWeiXinFriend() {
        if (checkApkExist(getContext(), PACKAGE_WECHAT)) {
            if (mShareUrl.endsWith(".jpg") || mShareUrl.endsWith(".png")) {
                shareImageToWeiXinFriend(mTitle + mShareUrl);
            } else {
                shareImageToWeiXinFriend(mTitle + mShareUrl);
//                shareLocalImageToWeiXinFriend();
//
//                Intent intent = new Intent();
//                ComponentName cop = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareImgUI");
//                intent.setComponent(cop);
//                intent.setAction(Intent.ACTION_SEND);
//                intent.putExtra(Intent.EXTRA_TEXT, getContext().getString(R.string.app_name)+'\n'+mTitle+'\n'+mShareUrl);
//                intent.putExtra(getContext().getString(R.string.app_name), "shareTextToWechatFriend");
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                getContext().startActivity(intent);
            }
        } else {
            ToastUtils.showToast("请先安装微信客户端");
        }
    }

    private void shareImageToWeiXinFriend(String shartStr) {
        if (checkApkExist(getContext(), PACKAGE_WECHAT)) {
            Intent intent = new Intent();
            ComponentName comp = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareToTimeLineUI");
            intent.setComponent(comp);
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");
            FileInfo fileInfo = new FileInfo();
            fileInfo.setUrl(mImageUrl);
            fileInfo.setFileName("yk_share_" + System.currentTimeMillis() + ".png");
            fileInfo.setFilePath(SPUtils.getImagePath());
            DownLoadUtils.getInstance().download(fileInfo, new DownLoadUtils.OnDownloadListener() {
                @Override
                public void onStartDownload() {

                }

                @Override
                public void onDownloading(long processed, long total) {

                }

                @Override
                public void onDownloadPause(long processed, long total) {

                }

                @Override
                public void onDownloadCancel(File file) {

                }

                @Override
                public void onDownloadSuccess(File file) {
                    if (file.exists()) {
                        Uri uri = Uri.fromFile(file);
                        intent.putExtra(Intent.EXTRA_STREAM, uri);
                        intent.putExtra("Kdescription", shartStr + "");
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        MyApp.myApp.startActivity(intent);
                    } else {
                        ToastUtils.showToast("分享失败");
                    }
                }

                @Override
                public void onDownloadFailed(Exception e) {
                    ToastUtils.showToast("分享失败");
                }
            });
        } else {
            ToastUtils.showToast("请先安装微信客户端");
        }

    }

    private void shareLocalImageToWeiXinFriend(String mImagePath, String shareStr) {
        if (checkApkExist(getContext(), PACKAGE_WECHAT)) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI"));
            intent.setAction(Intent.ACTION_SEND);

            File f = new File(mImagePath);
            Uri uri = null;
            if (f.exists()) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = getImageContentUri(getContext(), f);
                } else {
                    uri = Uri.fromFile(f);
                }
            } else {
                Toast.makeText(getContext(), "图片不存在", Toast.LENGTH_SHORT).show();
                return;
            }
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_STREAM, uri); //图片数据（支持本地图片的Uri形式）
            intent.putExtra("Kdescription", shareStr); //微信分享页面，图片上边的描述
            getContext().startActivity(intent);

        } else {
            ToastUtils.showToast("请先安装微信客户端");
        }

    }

    private void shareLocalImageToWeiXin() {
        if (checkApkExist(getContext(), PACKAGE_WECHAT)) {
            Intent intent = new Intent();
            ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");

            intent.setComponent(comp);
            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
            intent.setType("image/*");

            ArrayList<Uri> imageList = new ArrayList<>();
            File file = new File(mImagePath);
            if (file.exists()) {
                Uri uri = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    try {
                        uri = Uri.parse(MediaStore.Images.Media.insertImage(getContext().getContentResolver(), file.getAbsolutePath(), file.getName(), null));
                    } catch (FileNotFoundException e) {
                        Toast.makeText(getContext(), "图片不存在", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                } else {
                    uri = Uri.fromFile(file);
                }
                imageList.add(uri);
            }
            if (imageList.size() == 0) {
                Toast.makeText(getContext(), "图片不存在", Toast.LENGTH_SHORT).show();
                return;
            }
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageList); //图片数据（支持本地图片的Uri形式）
            getContext().startActivity(intent);

        } else {
            ToastUtils.showToast("请先安装微信客户端");
        }

    }

    private void shareImageToWeiXin() {
        if (checkApkExist(getContext(), PACKAGE_WECHAT)) {
            Intent intent = new Intent();
            ComponentName cop = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareImgUI");
            intent.setComponent(cop);
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");
            FileInfo fileInfo = new FileInfo();
            fileInfo.setUrl(mImageUrl);
            fileInfo.setFileName("yk_share_" + System.currentTimeMillis() + ".png");
            fileInfo.setFilePath(SPUtils.getImagePath());
            DownLoadUtils.getInstance().download(fileInfo, new DownLoadUtils.OnDownloadListener() {
                @Override
                public void onStartDownload() {

                }

                @Override
                public void onDownloading(long processed, long total) {

                }

                @Override
                public void onDownloadPause(long processed, long total) {

                }

                @Override
                public void onDownloadCancel(File file) {

                }

                @Override
                public void onDownloadSuccess(File file) {
                    if (file.exists()) {
                        mImagePath = file.getPath();
                        shareLocalImageToWeiXin();
                    } else {
                        ToastUtils.showToast("分享失败");
                    }
                }

                @Override
                public void onDownloadFailed(Exception e) {
                    ToastUtils.showToast("分享失败");
                }
            });
        } else {
            ToastUtils.showToast("请先安装微信客户端");
        }
    }

    private void shareToWeiXin() {
        if (checkApkExist(getContext(), PACKAGE_WECHAT)) {
            if (mShareUrl.endsWith(".jpg") || mShareUrl.endsWith(".png")) {
                shareImageToWeiXin();
            } else {
                Intent intent = new Intent();
                ComponentName cop = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareImgUI");
                intent.setComponent(cop);
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_TEXT, getContext().getString(R.string.app_name) + '\n' + mTitle + '\n' + mShareUrl);
                intent.putExtra(getContext().getString(R.string.app_name), "shareTextToWechatFriend");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getContext().startActivity(intent);
            }
        } else {
            ToastUtils.showToast("请先安装微信客户端");
        }
    }

    private void shareToMore() {
        if (!TextUtils.isEmpty(mImagePath)) {
            File file = new File(mImagePath);//这里share.jpg是sd卡根目录下的一个图片文件
            Uri imageUri = Uri.fromFile(file);
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
            shareIntent.setType("image/*");
            startActivity(Intent.createChooser(shareIntent, "分享图片"));
        } else {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain"); // 纯文本
            intent.putExtra(Intent.EXTRA_SUBJECT, "分享连接");
            intent.putExtra(Intent.EXTRA_TEXT, mShareUrl);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getContext().startActivity(Intent.createChooser(intent, ""));
        }
    }

//    private void shareToQQ(String plat) {
//        OnekeyShare oks = new OnekeyShare();
//        oks.setImageUrl(mImageUrl);
//        oks.setUrl(mImageUrl);
//        oks.setSiteUrl(mImageUrl);
//        oks.setTitleUrl(mShareUrl);
//        oks.setTitle("Matrix Photo");
//        oks.setText(mTitle);
//        oks.setPlatform(plat);
//        oks.show(getContext());
//    }
//
//    private void shareImageToQQ(String plat) {
//        Platform.ShareParams sp = new Platform.ShareParams();
//        sp.setShareType(Platform.SHARE_IMAGE);//设置分享为图片类型
//        sp.setImagePath(mImagePath);
//        Platform platform = ShareSDK.getPlatform(plat);// 要分享的平台//QQ.NAME
//        platform.share(sp);
//    }

    @Override
    public void onStart() {
        super.onStart();
        //得到dialog对应的window
        Window window = getDialog().getWindow();
        if (window != null) {
            //得到LayoutParams
            WindowManager.LayoutParams params = window.getAttributes();
            params.dimAmount = 0.6f;
            //修改gravity
            params.gravity = Gravity.BOTTOM;
            params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            window.setAttributes(params);
        }
    }


    public static boolean checkApkExist(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
        try {
            context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 获取分享到微信朋友圈的uri格式
     *
     * @param context
     * @param imageFile
     * @return
     */
    public static Uri getImageContentUri(Context context, File imageFile) {

        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        Uri uri = null;

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }
            cursor.close();
        }

        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        }
        return uri;
    }

}
